<template>
  <el-dialog title="库龄规则" :visible.sync="open" width="800px" append-to-body @close="reset">
  <el-form ref="formRef" :model="form" :rules="rules">
    <el-row :gutter="10" class="mb8" justify="end">
      <el-col :span="1.5">
<!--        <el-button
          type="primary"
          @click="handleAdd"
          :disabled="form.ageGroups.length >= 5"
        >
          新增行
        </el-button>-->
        <el-button
            type="primary"
            circle
            icon="el-icon-plus"
            @click="handleAdd"
            :disabled="form.ageGroups.length >= 5"
            class="custom-icon-btn"
            size="mini"
        />

      </el-col>
    </el-row>
    <el-table :data="form.ageGroups" style="width: 100%" border>
      <el-table-column label="分组名称" align="center">
        <template #default="{ row }" >
          {{row.endDays ? `${row.startDays}-${row.endDays}天`: `${row.startDays}天以上`}}
        </template>
      </el-table-column>
<!--      :disabled="$index !== 0"-->
      <el-table-column label="开始天数"  align="center">
        <template #default="{ row, $index }">
          <el-form-item :prop="`ageGroups.${$index}.startDays`" :rules="startDaysRules($index)" style="width: 100%"
          >
            <el-input
              v-model.number="row.startDays"
              :disabled="true"
              placeholder="开始天数"
            />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="结束天数"  align="center">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`ageGroups.${$index}.endDays`"
            :rules="endDaysRules($index)"
          >
            <el-input
              v-model.number="row.endDays"
              placeholder="结束天数"
              @change="handleEndDaysChange($index)"
            />
          </el-form-item>
        </template>
      </el-table-column>
<!--不显示-->
      <el-table-column label="最后天数" v-if="1==2" align="center">
        <template #default="{ row }">
          {{ row.endDays || '-' }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center">
        <template #default="{$index}">
<!--          <el-button
              type="danger"
              circle
              icon="el-icon-minus"
              @click="handleDelete($index)"
              :disabled="form.ageGroups.length === 1"
              class="custom-icon-btn"
              size="mini"
              link
          />-->

            <el-button
                v-if="$index === form.ageGroups.length - 1"
                type="danger"
                circle
                icon="el-icon-minus"
                @click="handleDelete($index)"
                :disabled="form.ageGroups.length === 1"
                size="mini"
                class="delete-btn"
                link
            />
        </template>
      </el-table-column>

    </el-table>

<!--    <div style="margin-top: 16px">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>-->

  </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listKuling, getKuling, delKuling, addKuling, updateKuling } from "@/api/mes/wm/kulingrule";
import {addMaterialconversions} from "@/api/mes/wm/materialconversions";
export default {
  data() {
    return {
      open:false,
      form: {
        ageGroups: [
          { startDays: 1, endDays: null }
        ]
      },
      rules: {
        ageGroups: {
          type: 'array',
          required: true,
          min: 1,
          max: 5,
          defaultField: {
            startDays: { type: 'number', required: true },
          }
        }
      }
    }
  },
  methods: {
    // 表单重置
    reset() {
      this.resetForm("formRef");
      this.form.ageGroups=[{ startDays: 1, endDays: null }]

      this.open=false
    },
    init(){
      this.open=true
    },
    // 新增行处理
    handleAdd() {

      const lastRow = this.form.ageGroups[this.form.ageGroups.length - 1]
      console.log("lastRow",lastRow)
      if (!lastRow.endDays || lastRow.endDays < lastRow.startDays) {
        this.$message.warning('请先填写前一行的结束天数')
        return
      }

      this.form.ageGroups.push({
        startDays: lastRow.endDays + 1,
        endDays: null
      })
    },

    // 删除行处理
    handleDelete(index) {
      if (this.form.ageGroups.length === 1) return
      this.form.ageGroups.splice(index, 1)

      // 调整后续行的startDays
      for (let i = index; i < this.form.ageGroups.length; i++) {
        if (i === 0) {
          this.form.ageGroups[i].startDays = 1
        } else {
          const prevRow = this.form.ageGroups[i - 1]
          this.form.ageGroups[i].startDays = prevRow.endDays + 1
          // 检查当前行endDays有效性
          if (this.form.ageGroups[i].endDays < this.form.ageGroups[i].startDays) {
            this.form.ageGroups[i].endDays = null
          }
        }
      }
    },

    // 结束天数变化处理
    handleEndDaysChange(index) {

      const currentRow = this.form.ageGroups[index]
      if(this.form.ageGroups.length != (index+1)){
        if (currentRow.endDays < currentRow.startDays) {
          this.$message.error('结束天数不能小于开始天数')
          currentRow.endDays = null
          return
        }
      }

      // 更新下一行startDays
      const nextIndex = index + 1
      if (nextIndex < this.form.ageGroups.length) {
        const nextRow = this.form.ageGroups[nextIndex]
        nextRow.startDays = currentRow.endDays + 1
        if (nextRow.endDays < nextRow.startDays) {
          nextRow.endDays = null
        }
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()

        // 二次校验
        let isValid = true
        for (let i = 0; i < this.form.ageGroups.length; i++) {
          const row = this.form.ageGroups[i]

          if (i === 0 && row.startDays !== 1) {
            this.$message.error('第一行开始天数必须为1')
            isValid = false
            break
          }

          if (i > 0) {
            const prevRow = this.form.ageGroups[i - 1]
            if (row.startDays !== prevRow.endDays + 1) {
              this.$message.error(`第${i + 1}行开始天数必须为前一行结束天数+1`)
              isValid = false
              break
            }
          }
        }

        if (isValid) {
          const submitData = this.form.ageGroups.map(row => ({
            groupName: row.endDays ? `${row.startDays}-${row.endDays}天`: `${row.startDays}天以上`,
            startDays: row.startDays,
            endDays: row.endDays,
            intervalDays: row.endDays,
            sortOrder: this.form.ageGroups.indexOf(row) + 1
          }))

          console.log("22222222222222",this.form)
          addKuling({'ageGroups':submitData}).then(response => {
            if(response.code == 200){
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.$emit('refreshDataList')
            }else {
              this.$modal.msgSuccess("添加失败");
            }

          });

        }
      } catch (error) {
        this.$message.error('表单校验失败')
      }
    },

    // 验证规则
    startDaysRules(index) {
      return [
        { required: true, message: '开始天数不能为空' },
        {
          validator: (rule, value, callback) => {
            if (index === 0 && value !== 1) {
              callback(new Error('第一行开始天数必须为1'))
            } else if (index > 0) {
              const prevRow = this.form.ageGroups[index - 1]
              if (value !== prevRow.endDays + 1) {
                callback(new Error('开始天数必须等于前一行结束天数+1'))
              }
            }
            callback()
          }
        }
      ]
    },

/*    endDaysRules(index) {
      return [
        { required: true, message: '结束天数不能为空' },
        {
          validator: (rule, value, callback) => {
            if (value < this.form.ageGroups[index].startDays) {
              callback(new Error('结束天数不能小于开始天数'))
            }
            callback()
          }
        }
      ]
    },*/
    isLastRow(index) {
      return index === this.form.ageGroups.length - 1;
    },
    endDaysRules(index) {
      return [
        {
          required: !this.isLastRow(index),
          message: '请输入结束天数',
          trigger: ['blur', 'change']
        },
        {
          validator: (rule, value, callback) => {
            if (value === null || value === undefined) {
              console.log("ssssssssss",value)
              if (this.isLastRow(index)) {
                callback();
              } else {
                callback(new Error('请输入结束天数'));
              }
            } else {
              const start = this.form.ageGroups[index].startDays;
              if(!this.isLastRow(index)){
                if (value < start) {
                  console.log("vvvvvvv",value)
                  callback(new Error('结束天数不能小于开始天数'));
                } else {
                  callback();
                }
              }

            }
          },
          trigger: ['blur', 'change']
        }
      ];
    }


  }
}
</script>
<style scoped>
 .mb8 {
  display: flex;
  justify-content: flex-end;
   margin-right: 45px !important;
}
/* 按钮样式优化 */
.custom-icon-btn {
  display: flex;
  justify-content: flex-end;
  padding: 6px;
  font-size: 12px;
}

/* 禁用状态样式 */
.el-button.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 鼠标悬停效果 */
.el-button:not(.is-disabled):hover {
  transform: scale(1.1);
  transition: transform 0.2s;
}
</style>
